package com.example.demo.redisToken;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author mrc
 * RedisToken工具类
 */
@Component
public class RedisToken {

    RedisUtil redisUtil;

    @Autowired
    public RedisToken(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    /**
     * 初始过期时间
     */
    private static final Long EXPIRE_TIME = 3600L;

    /**
     *     token名称
     */
    public static final String TOKEN_NAME = "access_token";

    /**
     * 更新token最低时间
     */
    private static final Long RENEW_TIME_LIMIT = 600L;

    /**
     * 续期token的时间
     */
    private static final Long RENEW_TIME = 600L;

    private static final String ID = "id";

    private static final String USER_NAME = "userName";

    private static final String ROLE = "role";

    private static final String IP = "ip";

    /**
     * 生成token
     * @param id
     * @param userName
     * @param role
     * @return
     */
    public String createToken(String id, String userName, Integer role, String ip) {
        JSONObject object = new JSONObject();
        object.put(ID, id);
        object.put(USER_NAME, userName);
        object.put(ROLE, role);
        object.put(IP, ip);
        String token = IdUtil.fastSimpleUUID();
        redisUtil.strSetEx(token, object.toJSONString(), EXPIRE_TIME);
        return token;
    }

    private boolean isTokenWillExpired(String token) {
        return redisUtil.strGetExpire(token) < RENEW_TIME_LIMIT;
    }

    public boolean isTokenExpired(String token) {
        boolean b = true;
        if (redisUtil.strHasKey(token)) {
            b = false;
            if (isTokenWillExpired(token)){
                redisUtil.strSetExpire(token, redisUtil.strGetExpire(token) + RENEW_TIME);
            }
        }
        return b;
    }

    public void logOut(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        redisUtil.strDel(token);
    }

    private JSONObject getSomeThingFormToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN_NAME);
        String val = redisUtil.strGet(token);
        return (JSONObject) JSONObject.parse(val);
    }

    public String getUsernameFromToken(HttpServletRequest request) {
        return getSomeThingFormToken(request).get(USER_NAME).toString();
    }

    public Integer getRoleFromToken(HttpServletRequest request) {
        return (Integer) getSomeThingFormToken(request).get(ROLE);
    }

    public Object getIdFromToken(HttpServletRequest request) {
        return getSomeThingFormToken(request).get(ID);
    }

    public String getIpFromToken(HttpServletRequest request) {
        return getSomeThingFormToken(request).get(IP).toString();
    }
}
